var util = require('../../../utils/util.js');
var ajax = require('../../../utils/ajax.js');
var common = require('../../../utils/common.js');
var PageBase = require('../../../common/PageBase.js');
var WxParse = require('../../../utils/wxParse/wxParse.js');
var app = getApp();

Page(common.extendPage(PageBase, {
  data: {
    isLogin: false,
    id: null,
    isHasAttr: 0, //是否有规格0 没有 1有
    actType: 0, //判断是什么活动的商品 0普通 1 秒杀 2团购
    isgroups: 1,
    dataLoaded: false,
    winHei: 0,
    swiperHei: 0,
    curSwiperIndex: 0,
    shop: {},
    curSkuItem: {
      skuId: '',
      price: '',
      amount: 0
    },
    skuList: [],
    skuJson: [],
    num: null,

    isMember: 0, 
    isHead: 0,

    groupid: null,
    groupsAll: [],
    teamid: '',


    //弹出浮层
    panel: {
      type: 1, //1.立即购买2.加入购物车
      isShow: false,
      aimation: {},
      opacityAnimation: {},
      height: 0,
      phone: '',
      yzm: '',
      yzmTime: 0
    },

    //库存计数器
    counter: {
      number: 1,
      minusDisabled: false,
      addDisabled: false,
    },

    canPay: false,
    //isCollected: false,
    cartAmount: 0,
    shareTitle: ""
  },

  onLoad(options) {
    common.initApp({
      extSuc: () => {
      },
      loginSuc: () => {
        this._fetch();
        this.setData({
          isLogin: !!app.getUid(),
        });
      }
    });
    this.setData({
      id: this.options.id,
      // isLogin: !!app.getUserSid(),
      // canPay: app.getCanPay(),
      winHei: app.getWinHei()
    });
  },

  _fetch() {
    var $this = this;
    ajax.G({
      url: 'm=goods&c=index&a=info&id=' + this.options.id,
      data: {
        uid: app.getUid()
      },
      success: (res) => {
        if (res.code == 1) {
          this.setData({
            dataLoaded: true
          })
          util.showWarn(res.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })
          }, 2500)
        };
        if (res.data.isgroups == 0 || res.data.groups.status == 1){
          //debugger;
          this.setData({
            dataLoaded: true
          });
          util.showWarn("拼团已结束");
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })
          }, 2500)

        }
        //debugger;
        if (res.data.groups.length <= 0) {

          this.setData({
            dataLoaded: true
          })
          util.showWarn("商品已经下架");
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })
          }, 2500)

        }
        //debugger;
        var goodsInfo = res.data;

        this.setData({
          shareTitle: goodsInfo.intro || goodsInfo.name
        })

        if (goodsInfo.content) {
          WxParse.wxParse('article', 'html', goodsInfo.content, this, 0);
        }

        if (goodsInfo.shop.length <= 0) {
          this.setData({
            isStore: 1,
            storeInfo: app.getStoreInfo()
          });
        }

        var feetrans, skulist=[], skuJson=[], groups;

        // 如果是团长
        if (typeof(goodsInfo.usergroups) != "undefined" && goodsInfo.usergroups.ishead == 1 ){
            this.setData({
               isHead: 1,
               isMember: 1
            })
        };
        // 如果是团员
        if (typeof (goodsInfo.usergroups) != "undefined" && goodsInfo.usergroups.ishead == 0 && goodsInfo.usergroups.isgroups == 1){
          this.setData({
            isMember: 1,
            isHead: 0
          })
        };


        // 如果有规格
        if (goodsInfo.attr.length > 0) {
          console.log("有规格");
          skulist = goodsInfo.attr;
          skuJson = goodsInfo.attrprice;
          //默认选中第一个
          if (skulist[0]) {
            skulist[0].data[0].selected = true;
          };
          if (!!skulist[1]) {
            skulist[1].data[0].selected = true;
          };
          // 有规格
          this.setData({
            dataLoaded: true,
            isHasAttr: 1,
            skuList: skulist,
            skuJson: skuJson,
            num: goodsInfo.num,
            goodsInfo
          });
          this._setSkuItem();
        }
        else {
          // 有规格
          this.setData({
            dataLoaded: true,
            num: goodsInfo.num,
            goodsInfo
          });
        };
        this.setData({
          groupid: goodsInfo.groups.id
        });
        // 获取购物车数量
        this._getCartAmount();
        this._getAllpt();
      }
    });
  },

  // 获取该商品所有拼团
  _getAllpt: function(){
    ajax.G({
      url: 'm=plugins&c=groups&a=groupsall',
      data: {
        id: this.data.id
      },
      success: (res) => {
        //debugger;
        var groupsAll = res.data;
        this.setData({
          groupsAll
        })
      }
    })
  },

  _tobuy: function(evt){
    //debugger;
    this.setData({
      teamid: evt.currentTarget.dataset.teamid
    });
    this._buy(evt);
  },

  /**
   * 获取购物车数量
   */
  _getCartAmount: function () {
    var self = this;
    if (!self.data.isLogin) {
      return;
    }
    ajax.G({
      url: "m=goods&c=cart",
      data: {
        uid: app.getUid()
      },
      success: (res) => {
        var cartList = res.data;
        var cartnum = 0;
        //debugger;
        cartList.forEach(function (item) {
          var goods = item.goods;
          cartnum += goods.length;
        });
        console.log(cartnum);
        this.setData({
          cartAmount: cartnum || 0
        })
      }
    });
  },

  //
  _validSubmit() {
    var self = this;
    if (self.data.isHasAttr == 1) {

      if (self.data.curSkuItem.amount != null) {
        if (self.data.counter.number > self.data.curSkuItem.amount) {
          util.alert('库存不足');
          return false;
        } else if (self.data.counter.number <= 0) {
          util.alert('请输入正确的购买数量哦~');
          return false;
        }
      }
      else {
        if (self.data.counter.number > self.data.num) {
          util.alert('库存不足');
          return false;
        } else if (self.data.counter.number <= 0) {
          util.alert('请输入正确的购买数量哦~');
          return false;
        }
      }

    }
    else {


    }

    return true;
  },


  /**
   * 立即购买
   */
  _buy: function (evt) {
    //var formId = evt.detail.formId;
    //common.submitForm(formId);
    //debugger;
    var buyType = evt.currentTarget.dataset.buytype;
    if (this.data.isLogin) {
      this._showPanel(buyType);
    } else {
      wx.navigateTo({
        url: '/pages/login/login'
      });
    }
  },

  /**
   * 倒计时
  */
  _timerDown: function (time) {
    var panel = this.data.panel;

    panel.yzmTime = --time;
    this.setData({
      panel
    });
    if (time == 0) {
      return;
    }
    setTimeout(function () {
      this._timerDown(time);
    }.bind(this), 1000);
  },

  /**
   * 展示购买浮层
   */
  _showPanel(ty) {
    var $this = this;
    var panel = this.data.panel;

    panel.type = ty;
    $this.animation = wx.createAnimation({
      duration: 200,
      timingFunction: "ease-out"
    });
    $this.opacityAnimation = wx.createAnimation({
      duration: 200,
      timingFunction: "ease-out"
    });

    panel.isShow = true;
    $this.setData({
      panel
    });

    setTimeout(function () {
      $this.animation.translateY(0).step();
      $this.opacityAnimation.opacity(1).step();

      panel.animation = $this.animation.export();
      panel.opacityAnimation = $this.opacityAnimation.export();

      $this.setData({
        panel
      });
    }, 0);
  },

  /**
   * 关闭购买浮层
   */
  _closePanel(evt) {
    var $this = this;
    var panel = this.data.panel;
    $this.animation.translateY('100%').step();
    $this.opacityAnimation.opacity(0).step();

    panel.animation = $this.animation.export();
    panel.opacityAnimation = $this.opacityAnimation.export();

    $this.setData({
      panel,
      dataLoaded: true
    })
    setTimeout(function () {
      panel.isShow = false;
      $this.setData({
        panel
      });
    }, 500)
    if (evt) {
      var formId = evt.detail.formId;
      //common.submitForm(formId);
    }

  },

  /**
   * sku变化时，重围计数器
   */
  _resetCounter() {
    //debugger;
    var amount = +this.data.curSkuItem.amount; //当前库存
    var counter = this.data.counter;

    if (counter.number > amount) {
      counter.number = amount;
    }

    counter.minusDisabled = counter.number <= 0;
    counter.addDisabled = counter.number >= amount;
    this.setData({
      counter
    });
  },

  /**
   * 计数器+
   */
  _add: function (evt) {
    var counter = this.data.counter;
    var formId = evt.detail.formId;
    var max = evt.currentTarget.dataset.max;

    if (max != undefined && ++counter.number > max) {
      counter.number = max;
    }
    if (counter.number == max && max == 0) {
      counter.addDisabled = true;
    } else if (counter.number == max && max != 0) {
      counter.addDisabled = true;
    } else {
      counter.minusDisabled = false;
    }
    this.setData({
      counter,
    });
    //common.submitForm(formId);
  },

  /**
   * 计数器-
   */
  _minus: function (evt) {
    var counter = this.data.counter;
    var formId = evt.detail.formId;
    var min = evt.currentTarget.dataset.min;

    if (min != undefined && --counter.number < min) {
      counter.number = min;
    }
    if (counter.number < 0) {
      counter.number = 0;
    }
    if (counter.number == min) {
      counter.minusDisabled = true;
    } else {
      counter.addDisabled = false;
    }

    this.setData({
      counter
    });
    //common.submitForm(formId);
  },

  /**
   * 计数量input输入
   */
  _changeNum: function (evt) {
    var val = parseInt(evt.detail.value) || 1;
    var counter = this.data.counter;

    counter.number = val;
    this.setData(counter);
  },

  /**
   * 根据窗口大小，初始化组件宽高
   */
  _initSizeByWin: function () {
    var $this = this;
    // var panel = this.data.panel;

    wx.getSystemInfo({
      success: function (res) {
        // panel.height = res.windowHeight * 0.85;
        $this.setData({
          swiperHei: res.windowWidth * 0.53,
          // panel
        });
      }
    })
  },

  /**
   * 重组sku列表数据结构
   */
  // _setSkuList() {
  //   var goodsSku = this._goodsSku;
  //   var skuList = this.data.skuList;

  //   Object.keys(goodsSku).forEach(function (key) {
  //     var skuArr = goodsSku[key];
  //     var skuItem = {
  //       text: key,
  //       skuArr: [],
  //     }

  //     skuArr.forEach(function (text, index) {
  //       skuItem.skuArr.push({
  //         text: text,
  //         selected: index == 0 ? true : false
  //       })
  //     });
  //     skuList.push(skuItem)
  //   });

  //   this.setData({
  //     skuList: skuList
  //   });
  // },

  /**
   * 设置当前选中sku,并修改显示的价格和库存
   */
  _setSkuItem() {
    //debugger;
    var $this = this;
    var skuList = this.data.skuList;
    //var skuJson = this._skuJson;
    var skuJson = this.data.skuJson;

    var curSkuItem;
    var selectedObj = {};

    skuList.forEach(function (group) {
      group.data.some(function (skuItem) {
        //debugger;
        if (skuItem.selected) {
          selectedObj[group.name] = skuItem.name;
          return true;
        }
      });
    });

    skuJson.some(function (sku) {
      //debugger;
      if (JSON.stringify(sku.name) == JSON.stringify(selectedObj)) {
        //debugger;
        curSkuItem = {
          skuId: sku.id,
          price: sku.price,
          amount: $this.data.num
        }
        return true;
      }
    });
    this.setData({
      curSkuItem: curSkuItem,
    });
    console.log(this.data.curSkuItem);
  },

  /**
   * swiper切换时
   */
  _swiperChange: function (evt) {
    this.setData({
      curSwiperIndex: evt.detail.current,
    });
  },

  /**
 * 预览图片
 */
  _previewImg: function (evt) {
    var formId = evt.detail.formId;
    wx.previewImage({
      current: this.data.imageUrls[this.data.curSwiperIndex],
      urls: this.data.imageUrls,
    })
    //common.submitForm(formId);
  },

  /**
   * 选择sku
   */
  _selectSku(evt) {
    //debugger;
    var {
      groupIndex,
      skuIndex
        } = evt.currentTarget.dataset;
    var skuList = this.data.skuList;
    var groupObj = skuList[groupIndex];

    groupObj.data.forEach(function (sku, index) {
      sku.selected = index == skuIndex;
    });

    this.setData({
      skuList: skuList,
    });

    //this._setSkuItem();
    //this._resetCounter();

  },

  /**
   * 确定下单
   */
  _confirmBuy(evt) {
    //debugger;
    var uid = app.getUid();
    var self = this;
    var formId = evt.detail.formId;

    if (!self._validSubmit()) {
      return;
    }

    quickBuy();

    function quickBuy() {
      self.setData({
        dataLoaded: false
      });
      var {
        actId,
        actType,
        groupBuyId,
        teamid
      } = self.options;

      // 规格id
      var aids = '';
      if (typeof(self.data.curSkuItem) == "undefined"){
          aids = '';
      }
      else{
        aids = self.data.curSkuItem.skuId;
      }
      if (self.data.teamid != "" && !!self.data.teamid){
        //debugger;
        var ajaxParams = {
          uid: uid,
          gids: self.data.id,
          aids: aids,
          nums: self.data.counter.number,
          isgroups: self.data.panel.type,
          teamid: self.data.teamid
        };
      }
      else{
        var ajaxParams = {
          uid: uid,
          gids: self.data.id,
          aids: aids,
          nums: self.data.counter.number,
          isgroups: self.data.panel.type
        };
      }

      ajax.P({
        url: 'm=order&c=add&a=tmp',
        data: ajaxParams,
        success: (res) => {
          //debugger;
          var tmpOrderId = res.data.id;
          self.setData({
            dataLoaded: true
          });
          self._closePanel();
          var skuId = '';
          if (typeof (self.data.curSkuItem) != "undefined"){
            skuId = self.data.curSkuItem.skuId;
          };

          wx.navigateTo({
            url: '../confirmOrder/index?goodsId=' + self.data.id + '&skuId=' + skuId + '&amount=' + self.data.counter.number + '&tmpOrderId=' + tmpOrderId + '&teamid=' + self.data.teamid
          })
        }
      });

    }

    // self._closePanel();
    // console.log(this.data.curSkuItem);
    // debugger
    // wx.navigateTo({
    //   url: '/pages/goods/confirmOrder/index?goodsId=' + self.data.goodsId
    // })
    //common.submitForm(formId);
  },


  onShareAppMessage: function (res) {
    return {
      title: this.data.shareTitle,
      path: '/pages/goods/detail2/detail?id=' + this.data.id,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  _showActionSheet() {
    this.onShareAppMessage();
    // var {
    //   goodsId,
    //   actId,
    //   actType
    //     } = this.options;
    // var {
    //         isFenxiao
    //     } = this.data;
    // var shareParams = {
    //   type: isFenxiao ? 2 : 1,
    //   goodsId: goodsId,
    // };

    // if (actId) { //活动
    //   if (actType == 0) { //秒杀
    //     shareParams.type = 5;
    //     shareParams.actId = actId;
    //   } else if (actType == 1) { //团购
    //     shareParams.type = 3;
    //     shareParams.actId = actId;
    //   }
    // }
    // this._shareAs.show(shareParams);
  }

}));